//
//  CTCContractVC.m
//  ConsultantVersion
//
//  Created by 李小龙 on 2017/3/24.
//  Copyright © 2017年 jieshuibao. All rights reserved.
//

#import "CTCContractVC.h"
#import "CTCContractCell.h"
#import "CTCContractModel.h"
#import "CTCContractDetailVC.h"
#import "CTCContractEditVC.h"

@interface CTCContractVC ()
@property (nonatomic, strong) NSMutableArray *contractsArr;
/** <#assign属性注释#> */
@property (nonatomic, assign) NSInteger lastId;
@end

@implementation CTCContractVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    DeLog(@"++++++++");
    [self setupNavBar];
    [self setupTableView];
    [self getNewContractsListData];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getNewContractsListData) name:kReloadContractListListNotification object:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self getTabBarRedBadgeData];
}

- (void)getTabBarRedBadgeData
{
    [RequestTool POST:kTabBarRedBadgeUrl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DeLog(@"kTabBarRedStatusURL---responseObject %@", responseObject);
        
        if ([responseObject[@"code"] integerValue] == 1) {
            
            if ([responseObject[@"data"][@"rapidRed"] integerValue]) {
                [self.tabBarController.tabBar.items[0] showBadge];
            } else {
                [self.tabBarController.tabBar.items[0] hidenBadge];
            }
            
            if (([responseObject[@"data"][@"oneRed"]  integerValue]) ||([responseObject[@"data"][@"lineDownRed"]  integerValue])) {
                [self.tabBarController.tabBar.items[1] showBadge];
            } else {
                [self.tabBarController.tabBar.items[1] hidenBadge];
            }
        }
        else {
            [MBProgressHUD showInfoMessage:responseObject[@"des"]];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DeLog(@"error %@", error);
        if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
            [MBProgressHUD showErrorMessage:@"网络不给力"];
        }
        else {
            [MBProgressHUD showErrorMessage:@"服务器繁忙"];
        }
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.contractsArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CTCContractCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CTCContractCell" forIndexPath:indexPath];
    if (self.contractsArr.count) {
        cell.contractModel = self.contractsArr[indexPath.section];
    }

    return cell;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CTCContractModel *model = self.contractsArr[indexPath.section];
    CTCContractDetailVC *vc = [[CTCContractDetailVC alloc]init];
//    vc.contractModel = model;
    vc.uuid = model.uuid;
    MPWeakSelf(self);
    vc.changeContractStatusBlock = ^(CTCContractStatusType contractStatusType){
        model.status = [NSString stringWithFormat:@"%ld",(long)contractStatusType];
        [weakself.tableView reloadSections:[[NSIndexSet alloc]initWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationFade];
    };
    [self.navigationController pushViewController:vc animated:YES];
}


- (void)getContractsListData
{
    
//    {
//        "pageIndex":1,
//        "pageEnd":3
//    }

    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"pageIndex"] = @(self.lastId);
    dic[@"pageEnd"] = @(self.lastId+9);
    
    [MBProgressHUD showAnimationHUD];
    [RequestTool POST:kContrctListUrl parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DeLog(@"responseObject+++++:%@",responseObject);
        [MBProgressHUD  hideHUD];
        [self stopRefresh];
        CTCContractListModel *model = [CTCContractListModel yy_modelWithJSON:responseObject];
        if ([model.code integerValue] == 1) {
            [self.contractsArr addObjectsFromArray:model.contractModelArr];
            self.lastId += model.contractModelArr.count;
            [self.tableView reloadData];
        } else {
            [MBProgressHUD showErrorMessage:model.des];
            if ([model.code integerValue]== 2) {
                CTCLoginViewController *vc = [CTCLoginViewController viewControllerFromStoryboard];
                MPWeakSelf(self);
                vc.loginSuccess = ^(){
                    [weakself getNewContractsListData];
                };
                [self presentViewController:vc animated:YES completion:nil];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DeLog(@"error+++++:%@",error);
        [self stopRefresh];
        if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
            [MBProgressHUD showErrorMessage:@"网络不给力，请检查网络"];
        }
        else {
            [MBProgressHUD showErrorMessage:@"服务器繁忙"];
        }
    }];
    
}



- (void)getNewContractsListData
{
    self.lastId = 1;
    [self.contractsArr removeAllObjects];
    [self getContractsListData];
}

- (void)getMoreContractsListData
{
    [self getContractsListData];
}



- (void)stopRefresh
{
    !self.tableView.mj_header.isRefreshing ? : self.tableView.mj_header.endRefreshing;
    !self.tableView.mj_footer.isRefreshing ? : self.tableView.mj_footer.endRefreshing;
}


-(void)setupNavBar
{
    self.title = @"审合同";
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"我要审合同" style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemClick)];
}


- (void)rightBarButtonItemClick
{
    CTCContractEditVC *vc = [[CTCContractEditVC alloc]init];
    MPWeakSelf(self);
    vc.commitContractReturnBlock = ^(){
        [weakself getNewContractsListData];
    };
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)setupTableView
{
    self.tableView.estimatedRowHeight = 200;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.sectionHeaderHeight = 10;
    self.tableView.sectionFooterHeight = 0;
    self.tableView.contentInset = UIEdgeInsetsMake(11-35, 0, 0, 0);
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(getNewContractsListData)];
    self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(getMoreContractsListData)];
}


- (NSMutableArray *)contractsArr
{
    if (!_contractsArr) {
        _contractsArr = [NSMutableArray array];
    }
    
    return _contractsArr;
}

- (NSInteger)lastId
{
    if (!_lastId) {
        _lastId = 1;
    }
    
    return _lastId;
}

@end
